package com.witframework.web.tag;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * Display the sources of the JSP file.
 */
public class ShowSourceTag extends TagSupport {
	String jspFile;

	public void setJspFile(String jspFile) {
		this.jspFile = jspFile;
	}

	public int doEndTag() throws JspException {
		if ((jspFile.indexOf("..") >= 0)// ||(jspFile.toUpperCase().indexOf("/WEB-INF/") != 0)
		)
			throw new JspTagException("Invalid file " + jspFile);
		//pageContext.getResponse().setCharacterEncoding("utf-8");
		InputStream in = pageContext.getServletContext().getResourceAsStream(
				jspFile);
		if (in == null)
			throw new JspTagException("Unable to find file: " + jspFile);		
		
		JspWriter out = pageContext.getOut();
		try {
			byte[] contentBytes=new byte[in.available()];
			in.read(contentBytes);
			String content=new String(contentBytes).replaceAll("<", "&lt;");
			content=content.replaceAll(">","&gt;");
			out.println("<pre>");	
			out.print(content);
			out.println("</pre>");

		} catch (IOException ex) {
			throw new JspTagException("IOException: " + ex.toString());
		}
		return super.doEndTag();
	}
}

